import captcha from "@/utils/captcha";
import { ClickCaptchaData, ClickCaptchaDot } from "../meta/data";
import { ClickCaptchaEvent } from "../meta/event";

// 处理器
export function useClickCaptchaHandler(
  _:ClickCaptchaData,
  event:ClickCaptchaEvent,
  clearCbs:()=>void) {

  // 点击点
  const dots = reactive<{list:Array<ClickCaptchaDot>}>({list:[]})
 
  // 控制验证码显示
  const isShow =reactive<{show:boolean}>({show:false})

  // 点击事件
  const clickEvent = (e:Event |any) => {
    const target = e.currentTarget
    const xy = captcha.getDomXY(target)

    const mouseX = e.pageX || e.clientX
    const mouseY = e.pageY || e.clientY

    const {domX,domY} =xy

    const xPos = mouseX - domX
    const yPos = mouseY - domY
    const xx = parseInt(xPos.toString())
    const yy = parseInt(yPos.toString())
    const date = new Date()
    const index = dots.list.length
    dots.list.push({
      key:date.getTime(),
      index: index+1,
      x:xx,
      y:yy
    })
    event.click && event.click(xx,yy)
    e.cancelBubble = true
    e.preventDefault()
    return false
  }

  // 确认点击事件
  const confirmEvent = (e:Event | any) => {
    event.confirm && event.confirm(toRaw(dots.list),()=> {
      resetData()
    })
    e.cancelBubble = true
    e.preventDefault()
    return false
  }

  // 关闭事件
  const closeEvent = () => {
    event.close && event.close()
    resetData()
    isShow.show = false
  }

  // 刷新事件
  const refreshEvent = () => {
    event.refresh && event.refresh()
    resetData()
  }
  
  // 清理
  const clearData = () => {
    resetData()
    clearCbs && clearCbs()
  }
  
  // 刷新
  const refresh = () => {
    event.refresh && event.refresh()
    resetData()
  }

  // 关闭
  const close = () => {
    event.close && event.close()
    isShow.show = false
    resetData()
  }

  // 重置数据
  const resetData = () => {
    dots.list = []
    clearCbs()
  }

  // 展示
  const show = () => {
    isShow.show = true
  }
 
  return {
    dots,
    isShow,
    clickEvent,
    confirmEvent,
    closeEvent,
    refreshEvent,
    clearData,
    refresh,
    close,
    show,
    resetData
  }
}
